package cn.wizzer.app.task.commons.ext.quartz.job;


import cn.wizzer.app.crown.modules.services.order.CrownOrderService;
import cn.wizzer.app.sys.modules.services.SysTaskService;
import cn.wizzer.app.user.modules.models.TrialFund;
import cn.wizzer.app.user.modules.services.TrialFundService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Times;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.quartz.Job;
import org.quartz.JobExecutionContext;

import java.util.List;


/**
 * 体验金收回
 */
@IocBean
public class TrialFundTakeBackJob implements Job {

    private static final Log log = Logs.get();

    @Inject
    @Reference(retries = 0, timeout = 500000)
    private TrialFundService trialFundService;

    @Inject
    @Reference(retries = 0, timeout = 500000)
    private CrownOrderService crownOrderService;

    @Inject
    @Reference
    private SysTaskService sysTaskService;

    @Override
    public void execute(JobExecutionContext context) {
        log.info("体验金收回定时任务开始");
        // 查询体验金发放时间大于等于3天的
        List<TrialFund> list = trialFundService.query(Cnd.where("ctAt", "<=", Times.getTS() - 259200)
                .and("track", "=", false));
        list.forEach(trialFund -> crownOrderService.takeBack(trialFund.getUserId()));


        // 查询体验金发放时间大于等于30天的
        List<TrialFund> list30 = trialFundService.query(Cnd.where("ctAt", "<=", Times.getTS() - 2592000)
                .and("profit30", "=", false));
        list30.forEach(trialFund -> crownOrderService.takeBack30(trialFund.getUserId()));
        log.info("体验金收回定时任务结束");
        String taskId = context.getJobDetail().getKey().getName();
        sysTaskService.update(Chain.make("exeAt", (int) (System.currentTimeMillis() / 1000))
                .add("exeResult", "执行成功"), Cnd.where("id", "=", taskId));
    }
}
